// Copyright (c) 2005, Robin Ward
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted 
// provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the 
// following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and 
// the following disclaimer in the documentation and/or other materials provided with the distribution.
//
// Neither the name of the Robotic Jelly nor the names of its contributors may be used to endorse or 
// promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED 
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
// POSSIBILITY OF SUCH DAMAGE.

#import "Controller.h"
#import "EditorView.h"

@implementation Controller

- init
{
	if (self = [super init]) {
        currentFont = [[NSFont systemFontOfSize:[NSFont systemFontSize]] retain];
		
		content = nil;
		
		currentColor = [[NSColor blackColor] retain];
		
		pageNumber = 0;
		[progress setDoubleValue: 0];   
    }

	return self;
}

- (IBAction) openCustomAboutWindow:(id) sender
{ 
       if (![NSBundle loadNibNamed:@"About.nib" owner:self])
       {
           NSLog(@"Load ofAbout.nib failed");
           return;
       }
	   
	   [aboutWindow makeKeyAndOrderFront:nil];
}

-(void) awakeFromNib
{
	[self displayFontInfo];
}

-(void) dealloc
{
    [currentFont release];
	[super dealloc];
}

- (IBAction) preview:(id) sender
{ 
	[preview display];
}
 
- (int) marginWidth
{
	return [marginEntry intValue];
}

- (NSString *) textContent
{
	return content;
}

- (IBAction) openTextFile:(id) sender
{
    int result;
    NSArray *fileTypes = [NSArray arrayWithObjects: @"txt", @"text", NSFileTypeForHFSTypeCode( 'TEXT' ), nil];   
						
	NSOpenPanel *oPanel = [NSOpenPanel openPanel];
    [oPanel setAllowsMultipleSelection:NO];

    result = [oPanel runModalForDirectory:NSHomeDirectory()
                    file:nil types:fileTypes];

    if (result == NSOKButton) {

        NSArray *filesToOpen = [oPanel filenames];

        int i, count = [filesToOpen count];

        for (i=0; i<count; i++) {
			[self loadTextFile: [filesToOpen objectAtIndex:i]];
        }
    }

}

- (IBAction) chooseFont:(id) sender
{
	NSColorPanel *colorPanel = [NSColorPanel sharedColorPanel]; 
	[colorPanel setAction:@selector(changeFormatColor:)];
    [colorPanel setTarget:self];
	
	NSFontManager *fontManager = [NSFontManager sharedFontManager];
	[fontManager setAction:@selector(changeFormatFont:)];
    [fontManager setSelectedFont:currentFont isMultiple:NO];
    [fontManager orderFrontFontPanel:nil];
}


// Called when the font color changes
- (void)changeFormatColor:(id)sender
{
	NSColorPanel *colorPanel = [NSColorPanel sharedColorPanel]; 
	[self setCurrentColor:[colorPanel color]];
	[preview display];	
}

// Called when the font formatting changes
- (void)changeFormatFont:(id)sender
{
    NSFontManager *fontManager = [NSFontManager sharedFontManager];
    [self setCurrentFont:[fontManager convertFont:[fontManager selectedFont]]];
	[preview display];
}

- (void)setCurrentFont:(NSFont *)font
{
    NSFont *newFont = [font retain];
    [currentFont release];
    currentFont = newFont;
	[self displayFontInfo];

}

- (void) setCurrentColor:(NSColor *) colour
{
	NSColor *newColor = [colour retain];
	[currentColor release];
	currentColor = newColor;
}

- (NSFont *) previewFont
{
	return currentFont;
}

- (NSColor *) previewColor
{
	return currentColor;
}


// For loading a background image
- (IBAction) loadBackground:(id) sender
{
    int result;

	NSOpenPanel *panel = [NSOpenPanel openPanel];
    [panel setAllowsMultipleSelection:NO];
	[panel setTitle:NSLocalizedStringFromTable(@"LOAD_BACKGROUND_IMAGE", @"Localizable", @"")];
	
    result = [panel runModalForDirectory:NSHomeDirectory()
                    file:nil types:[NSImage imageFileTypes]];

    if (result == NSOKButton) {

        NSArray *filesToOpen = [panel filenames];

        int i, count = [filesToOpen count];

        for (i=0; i<count; i++) {
			NSImage *back = [[NSImage alloc] initWithContentsOfFile: [filesToOpen objectAtIndex:i]];
			
			if (back != nil) 
			{
				[back setSize:[preview bounds].size];
				[back setScalesWhenResized:YES];
				
				[preview setBackgroundImage: back];
				[opacityEntry setEnabled:YES];
			}
		}
    }
}

- (float) opacity
{
	return [opacityEntry floatValue];
}

// Loads a text file
- (void) loadTextFile: (NSString *) openFileName
{
	[content release];
	content = [[NSString stringWithContentsOfFile:openFileName] retain];
	
	if (content != nil && [content length] > 0)
	{
		[saveJPEGButton setEnabled:YES];
	}
	
	[preview display];
}

- (void) displayFontInfo
{
	[fontInfo setStringValue:[NSString stringWithFormat:@"%@ %.0f", [currentFont fontName], [currentFont pointSize]]];
}


- (IBAction) export:(id) sender
{
	NSOpenPanel *panel = [NSOpenPanel openPanel];
    [panel setAllowsMultipleSelection:NO];
	[panel setCanChooseDirectories:YES];
	[panel setCanChooseFiles:NO];
	[panel setTitle:NSLocalizedStringFromTable(@"CHOOSE_OUTPUT_DIR", @"Localizable", @"")];
	[panel setPrompt:NSLocalizedStringFromTable(@"EXPORT", @"Localizable", @"")];
	 
	if( [panel respondsToSelector:@selector(_setIncludeNewFolderButton:)] )
		[panel _setIncludeNewFolderButton:YES];
	else if( [panel respondsToSelector:@selector(setIncludeNewFolderButton:)] )
		[panel setIncludeNewFolderButton:YES];
	else 
		NSLog(@"Couldn't enable New Folder-button." );

    int result = [panel runModalForDirectory:NSHomeDirectory()
                    file:nil types:nil];

    if (result == NSOKButton) {
		
        NSArray *filesToOpen = [panel filenames];

        int i, count = [filesToOpen count];

        for (i=0; i<count; i++) {
			 [NSThread detachNewThreadSelector:@selector(saveJPEG:) toTarget:self withObject:[[filesToOpen objectAtIndex:i] stringByAppendingString:@"/"]];
        }
    }
}

- (void) saveJPEG:(id) outputDirectory
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

	// Disable all our controls first
	[saveJPEGButton setEnabled:NO];
	[importButton setEnabled:NO];
	[marginEntry setEnabled:NO];
	[quality setEnabled:NO];
	[filename setEnabled:NO];
	[changeBackgroundButton setEnabled:NO];
	[changeFontButton setEnabled:NO];
	
	[preview display];
	
    NSBitmapImageRep * bitmap = [NSBitmapImageRep alloc];
    
    [preview lockFocus];
    [bitmap initWithFocusedViewRect:[preview bounds]];
    [preview unlockFocus];
	
	id jpeg;

	NSDictionary *compression = [NSDictionary dictionaryWithObjectsAndKeys: 
			[NSNumber numberWithFloat:[quality floatValue]], NSImageCompressionFactor, 
			nil];

	jpeg = [bitmap representationUsingType:NSJPEGFileType properties:compression];
	
	NSString *saveFile = [outputDirectory stringByAppendingString:[[filename stringValue] stringByAppendingFormat:@"-%0.5d", pageNumber]];
	
	saveFile = [saveFile stringByAppendingPathExtension:@"jpg"];
	
	[jpeg writeToFile:saveFile atomically:YES];
		
	[preview advancePage];
	pageNumber++;
	
	float progressRatio = (((float) [preview offsetDisplayed]) / [content length]);
	
	if (progressRatio > [progress doubleValue])
	{	
		[progress setDoubleValue: progressRatio];
		[progress display];
	}
	
	if (progressRatio < 1.0f)
		[self saveJPEG:outputDirectory];
	else 
	{
		// Enable everything
		[saveJPEGButton setEnabled:YES];
		[marginEntry setEnabled:YES];
		[quality setEnabled:YES];
		[filename setEnabled:YES];	
		[importButton setEnabled:YES];
		[changeBackgroundButton setEnabled:YES];
		[changeFontButton setEnabled:YES];
		
		pageNumber = 0;
		[preview reset];
		[progress setDoubleValue: 0.0];
		
	}
	
	[pool release];
}


// To handle closing the app
- (BOOL)windowShouldClose:(NSWindow *)sender 
{
	[application terminate: self];
	return TRUE;
}

@end
